package org.robot.scm.infra;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

/**
 * @Author : Awn create on 2023/8/5 14:44
 */
@Slf4j
public class LocalCacheHelper {

    private static final Map<String, List<String>> localCacheMap = Maps.newConcurrentMap();

    /**
     * 如果之前的key存在则覆盖存入
     */
    public static void put(String key, String value) {
        localCacheMap.put(key, Lists.newCopyOnWriteArrayList(Lists.newArrayList(value)));
    }

    /**
     * 追加，不存在新增再存入
     */
    public static void append(String key, String value) {
        localCacheMap.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>()).add(value);
    }

    public static String get(String key) {
        List<String> strings = localCacheMap.get(key);
        if (CollectionUtils.isNotEmpty(strings)) {
            return strings.get(0);
        }
        return null;
    }

    public static List<String> getList(String key) {
        return localCacheMap.get(key);
    }

    public static void remove(String key) {
        localCacheMap.remove(key);
    }

    public static void clear() {
        localCacheMap.clear();
    }
}
